// pages/tianjia/tianjia.js
Page({
  data: {
    isSearching: false,
    devices: []
  },

  // 开始搜索设备
  startSearch() {
    this.setData({ isSearching: true });
    
    wx.showLoading({ title: '搜索中...', mask: true });
    
    wx.openBluetoothAdapter({
      success: () => {
        this.startDiscovery();
      },
      fail: (err) => {
        console.error('初始化失败', err);
        wx.showToast({ title: '请开启手机蓝牙', icon: 'none' });
        this.setData({ isSearching: false });
      }
    });
  },
  
  // 开始设备发现
  startDiscovery() {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: (res) => {
        this.listenDevices();
        setTimeout(() => {
          wx.stopBluetoothDevicesDiscovery();
          wx.hideLoading();
        }, 5000);
      },
      fail: (err) => {
        console.error('搜索失败', err);
        wx.hideLoading();
        this.setData({ isSearching: false });
      }
    });
  },

  // 监听发现设备
  listenDevices() {
    wx.onBluetoothDeviceFound((res) => {
      const devices = res.devices.filter(device => device.name);
      this.processDevices(devices);
    });
  },

  // 处理设备列表
  processDevices(devices) {
    const newDevices = devices.map(device => ({
      name: device.name || '未知设备',
      deviceId: device.deviceId,
      connecting: false,
      connected: false
    }));
    
    const existingIds = this.data.devices.map(d => d.deviceId);
    const filteredDevices = newDevices.filter(d => !existingIds.includes(d.deviceId));
    
    this.setData({
      devices: [...this.data.devices, ...filteredDevices]
    });
  },

  // 连接设备（修改重点）
  connectDevice(e) {
    const device = e.currentTarget.dataset.device;
    const deviceId = device.deviceId;
    
    const updatedDevices = this.data.devices.map(d => {
      if (d.deviceId === deviceId) {
        return { ...d, connecting: true };
      }
      return d;
    });
    this.setData({ devices: updatedDevices });
    
    wx.createBLEConnection({
      deviceId,
      success: () => {
        // 连接成功后跳转首页
        wx.showToast({
          title: '连接成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            // 保存设备并跳转
            wx.setStorageSync('connectedDevice', device);
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/zhuye/zhuye'  // 强制返回首页
              });
            }, 1500);
          }
        });
      },
      fail: (err) => {
        console.error('连接失败', err);
        wx.showToast({ title: '连接失败', icon: 'none' });
        const resetDevices = this.data.devices.map(d => {
          if (d.deviceId === deviceId) {
            return { ...d, connecting: false };
          }
          return d;
        });
        this.setData({ devices: resetDevices });
      }
    });
  },

  // 页面卸载时强制返回首页（防止用户手动返回）
  onUnload() {
    wx.stopBluetoothDevicesDiscovery();
    wx.reLaunch({
      url: '/pages/zhuye/zhuye'
    });
  }
  
});